package org.hybre.seed.core.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.transaction.annotation.Transactional;

import org.hybre.seed.core.model.User;

@Transactional
public class UserManagerImpl implements UserManager {
	private EntityManager em;
	static Log log = LogFactory.getLog(UserManagerImpl.class);

	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@SuppressWarnings("unchecked")
	public List<User> findAll() {
		Query query = getEntityManager().createQuery("select p FROM User p");

		return query.getResultList();
	}

	public User findByName(String name) {
		try {
			User pByWhere = (User) em.createQuery(
					"SELECT p from User p where firstName='" + name + "'")
					.getSingleResult();
			return pByWhere;
		} catch (NoResultException nre) {
			return null;
		}
	}

	public void save(User person) {
		if (person.getId() == null) {
			// new
			em.persist(person);
		} else {
			// update
			em.merge(person);
		}
	}

	public void remove(int id) {
		User person = find(id);
		if (person != null) {
			em.remove(person);
		}
	}

	private EntityManager getEntityManager() {
		return em;
	}

	public User find(int id) {
		return em.find(User.class, id);
	}

}
